<template>
  <div>
    <el-upload
        class="upload-demo"
        ref="upload"
        :multiple="true"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
    >
      <el-button
          style="margin-right: 10px;"
          slot="trigger"
          size="small"
          type="primary">
        选取视频文件
        <i class="el-icon-folder-add"></i>
      </el-button>
      <el-select v-model="selectedAudioFormat" placeholder="请选择转换的音频格式" class="audio-select" size="small">
        <el-option
            v-for="option in audioFormatOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
        />
      </el-select>
      <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="handleUploadVideos"
      >
        上传到服务器
        <i class="el-icon-upload"></i>
      </el-button>
      <div slot="tip" class="el-upload__tip">
        <i class="el-icon-info"></i>
        支持视频格式：mp4、avi、flv、mov、mpeg
        <br>
        <i class="el-icon-info"></i>
        视频大小限制：小于500MB
      </div>
    </el-upload>

    <div class="container">
      <el-button size="mini" @click="downloadAllAudios()" class="right-btn-left">
        全部下载
        <i class="el-icon-download"></i>
      </el-button>
      <el-button size="mini" type="danger" @click="deleteAllAudios()" class="right-btn-right">
        清空列表
        <i class="el-icon-delete"></i>
      </el-button>
    </div>

    <!-- 分割线 -->
    <el-divider></el-divider>
    <!-- 音频列表 -->
    <h1>音频列表</h1>
    <!-- 分割线 -->
    <el-divider></el-divider>
    <el-table
        :data="filteredTableData"
        style="width: 100%"
    >
      <el-table-column label="序号" type="index" :index="indexMethod"  align="center"></el-table-column>
      <el-table-column label="日期" prop="uploadTime"  align="center">
        <template slot-scope="scope">
          {{new Date(scope.row.uploadTime).toLocaleString()}}
        </template>
      </el-table-column>
      <el-table-column label="音频名" prop="audioName"  align="center"></el-table-column>
      <el-table-column label="音频类型" prop="audioFormat"  align="center"></el-table-column>
      <el-table-column label="音频大小" prop="audioSize"  align="center"></el-table-column>
      <el-table-column align="right">
        <template slot="header" slot-scope="{scope}">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索"></el-input>
        </template>
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleDownload(row.audioId, row.audioName, row.audioFormat)">
            下载
            <i class="el-icon-download"></i>
          </el-button>
          <el-button size="mini" type="danger" @click="deleteAudio(row.audioId)">
            删除
            <i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination align="right" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                   :current-page="pageIndex" :page-sizes="[10, 20, 50]" :page-size="pageSize" :total="totalCount"
                   layout="total, sizes, prev, pager, next, jumper"></el-pagination>
  </div>
</template>
import dayjs from 'dayjs'
<script>
export default {
  data() {
    return {
      fileList: [],
      tableData: [],
      search: "",
      checkInactiveIntervalId: null,
      audioFormatOptions: [
        {label: "MP3", value: "mp3"},
        {label: "WAV", value: "wav"},
        {label: "OGG", value: "ogg"},
        {label: "FLAC", value: "flac"}
      ],
      selectedAudioFormat: "",
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0
    };
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(data => !this.search || data.audioName.toLowerCase().includes(this.search.toLowerCase()));
    }
  },
  //当用户五分钟没有操作该页面时,清空上传记录,返回空页面
  mounted() {
    // 每次页面加载时自动更新列表
    this.loadAllAudios();

    /*let lastActiveTime = Date.now();

    document.addEventListener("click", () => {
      lastActiveTime = Date.now();
    });

    this.checkInactiveIntervalId = setInterval(() => {
      if ((Date.now() - lastActiveTime) > 5 * 60 * 1000) {
        let url = "/api/audios/clear";
        console.log("url = " + url);
        this.axios
            .get(url)
            .then((response) => {
              this.loadAllAudios();
              console.log("服务器数据已清空");
            })
            .catch((error) => {
              console.log("清空服务器数据时出错：", error);
            });
      }
    }, 60 * 1000);*/
  },

  // 在组件销毁前清除定时器,避免内存泄漏
  /*beforeUnmount() {
    clearInterval(this.checkInactiveIntervalId);
  },*/

  methods: {
    loadAllAudios() {
      let data = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
      };
      let config = {
        headers: {
          'Content-Type': 'application/json'
        },
        data: data
      };

      let url = "/api/audios/selectAll";
      console.log("url = " + url);
      this.axios.post(url, data, config).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.code == 200) {
          this.tableData = jsonResult.data.list;
          this.totalCount = jsonResult.data.totalCount;
          console.log(jsonResult);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch((error) => {
        console.error(error);
      });
    },

    // 上传多个视频文件并转换为音频文件
    handleUploadVideos() {
      const videoFiles = this.$refs.upload.uploadFiles;
      if (!videoFiles || videoFiles.length === 0) {
        this.$message.warning("请选择文件！");
        return;
      }

      if (!this.selectedAudioFormat) {
        this.$message.warning("请选择转换的音频格式！");
        return;
      }

      const formData = new FormData();
      for (let i = 0; i < videoFiles.length; i++) {
        formData.append("files", videoFiles[i].raw);
      }
      formData.append("audioFormat", this.selectedAudioFormat);

      let url = "/api/audios/videosUpload";
      this.axios.post(url, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
          .then((response) => {
            let jsonResult = response.data;
            if (jsonResult.code == 202) {
              // this.$alert(jsonResult.message);
			  this.$message({
			  	message: jsonResult.message,
			  	type: 'success',
			  	duration: 1200
			  });
              this.loadAllAudios();
              //清空上传列表
              this.$refs.upload.clearFiles();
            } else {
              if (jsonResult.code == null) {
                let title = '操作失败';
				this.$message({
					message: jsonResult.message,
					type: 'error',
					duration: 1200
				});
                // this.$alert(jsonResult.message, title, {
                //   confirmButtonText: '确定',
                //   callback: action => {
                //   }
                // });
              } else {
                this.$message.error(jsonResult.message);
                //清空上传列表
                this.$refs.upload.clearFiles();
              }
            }
          })
          .catch((error) => {
            console.error(error);
          });
    },

    // 下载单个文件
    handleDownload(audioId, audioName, audioFormat) {
      let url = "/api/audios/" + audioId + "/downloadAudioFile";
      console.log("url = " + url);
      this.axios.get(url, {
        responseType: "blob",
      })
          .then((response) => {
            let jsonResult = response.data;
            const url = window.URL.createObjectURL(new Blob([jsonResult]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", audioName + "." + audioFormat);
            document.body.appendChild(link);
            link.click();
          })
          .catch((error) => {
            console.error(error);
          });
    },

    // 下载全部文件
    downloadAllAudios() {
      if (this.tableData.length === 0) {
        this.$message.warning("没有可下载的文件,请上传！");
        return;
      }

      let url = "/api/audios/0/downloadAudioFile";
      console.log("url = " + url);
      this.axios.get(url, {
        responseType: "blob",
      })
          .then((response) => {
            let jsonResult = response.data;
            const url = window.URL.createObjectURL(new Blob([jsonResult]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "audios.zip");
            document.body.appendChild(link);
            link.click();
          })
          .catch((error) => {
            console.error(error);
          });
    },

    // 删除单个音频文件
    deleteAudio(audioId) {
		this.$confirm("确定要删除选中的记录？","提示",{
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning"
    }).then(() => {
      let url = "/api/audios/" + audioId + "/deleteAudioById";
      this.axios.post(url).then(resp=>{
        let jsonResult = resp.data;
        if(jsonResult.code==203){
          this.$message({
            message: jsonResult.message,
            type: 'success',
            duration: 1200
          })
          this.loadAllAudios();
        }
      })
    }).catch(() => {
    });
      // this.$confirm("您确认删除该文件吗?此操作不可撤销!","提示",()=>{
      //   let url = "/api/audios/" + audioId + "/deleteAudioById";
      //   console.log("url = " + url);
      //   this.axios.post(url)
      //       .then((response) => {
      //         let jsonResult = response.data;
      //         if (jsonResult.code == 203) {
      //           this.$alert(jsonResult.message);
      //           this.loadAllAudios();
      //         } else {
      //           let title = '操作失败';
      //           this.$alert(jsonResult.message, title, {
      //             confirmButtonText: '确定',
      //             callback: action => {
      //             }
      //           });
      //         }
      //       })
      //       .catch((error) => {
      //         console.error(error);
      //       });
      // }) 
    },

    // 删除所有音频文件
    deleteAllAudios() {
      if (this.tableData.length === 0) {
        this.$message.warning("没有可删除的文件,请上传！");
        return;
      }

      if (this.$confirm("您确认删除所有文件吗?此操作不可撤销!")) {
        let url = "/api/audios/clear";
        console.log("url = " + url);
        this.axios.post(url).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.code == 203) {
            this.$alert(jsonResult.message);
            this.loadAllAudios();
          } else {
            let title = '操作失败';
            this.$alert(jsonResult.message, title, {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
          }
        })
            .catch((error) => {
              console.error(error);
            });
      }
    },

    // 删除待上传列表中的文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    sizeChangeHandle: function(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.loadAllAudios();
    },
    currentChangeHandle: function(val) {
      this.pageIndex = val;
      this.loadAllAudios();
    },
    indexMethod(index) {
      return index + 1;
    },
  }
};
</script>

<style>
.container {
  position: relative;
  bottom: 10px;
}

.right-btn-right {
  position: absolute;
  top: 0;
  right: 0;
}

.right-btn-left {
  position: absolute;
  top: 0;
  right: 93px;
}
</style>

